from ai_manager import AIManager
from ai_assistants import (
    DataAnalysisAssistant, ImageGenerationAssistant,
    TextGenerationAssistant, TranslationAssistant, VoiceAssistant
)


def init_default_assistants(manager):
    """初始化默认AI助手（文档示例数据）"""
    default_assistants = [
        VoiceAssistant(101, "小智", "v1.2", True, 85, ["小爱同学引擎"]),
        TextGenerationAssistant(102, "文小助", "v2.0", True, 92, ["诗歌", "代码", "文案"]),
        ImageGenerationAssistant(103, "图灵", "v1.5", False, 88, "4K"),
        DataAnalysisAssistant(104, "数小析", "v1.0", True, 79, ["CSV", "Excel", "JSON"]),
        TranslationAssistant(105, "翻译精灵", "v2.1", False, 95, ["中-英", "中-日", "中-韩"])
    ]
    for ass in default_assistants:
        manager.add_assistant(ass)


def show_menu():
    """显示系统菜单"""
    print("\n========== 🤖AI助手管理器 ==========")
    print("1. 查看所有AI助手列表")
    print("2. 根据ID查询助手详情")
    print("3. 添加新的AI助手")
    print("4. 根据ID修改助手信息")
    print("5. 删除AI助手（按ID）")
    print("6. 启动AI助手服务")
    print("7. 停止AI助手服务")
    print("8. 为AI助手分配任务")
    print("9. 显示系统统计信息")
    print("0. 退出系统")
    print("===================================")
    return input("请选择操作: ")


def handle_add_assistant(manager):
    """处理添加新助手逻辑"""
    try:
        aid = int(input("请输入ID: "))
        name = input("请输入名称: ")
        ass_type = input("请输入类型（数据分析/图片生成/文本生成/翻译/语音）: ")
        version = input("请输入版本号: ")
        is_online = bool(int(input("是否在线？(1-是, 0-否): ")))
        ability_score = int(input("请输入能力评分(0-100): "))

        # 根据类型创建对应子类对象
        if ass_type == "数据分析":
            support_formats = input("请输入支持的数据格式（用逗号分隔）: ").split(",")
            new_ass = DataAnalysisAssistant(aid, name, version, is_online, ability_score, support_formats)
        elif ass_type == "图片生成":
            max_res = input("请输入最大分辨率（如4K）: ")
            new_ass = ImageGenerationAssistant(aid, name, version, is_online, ability_score, max_res)
        elif ass_type == "文本生成":
            text_types = input("请输入支持的文本类型（用逗号分隔）: ").split(",")
            new_ass = TextGenerationAssistant(aid, name, version, is_online, ability_score, text_types)
        elif ass_type == "翻译":
            langs = input("请输入支持的语言（用逗号分隔，如中-英）: ").split(",")
            new_ass = TranslationAssistant(aid, name, version, is_online, ability_score, langs)
        elif ass_type == "语音":
            engine = input("请输入语音引擎（用逗号分隔）: ").split(",")
            new_ass = VoiceAssistant(aid, name, version, is_online, ability_score, engine)
        else:
            print("❌ 无效类型！仅支持：数据分析/图片生成/文本生成/翻译/语音")
            return

        success, msg = manager.add_assistant(new_ass)
        print(msg)
    except ValueError:
        print("❌ 输入格式错误！ID和能力评分需为数字，在线状态需为1或0。")


def main():
    """系统主函数"""
    print("欢迎使用 AI助手管理器 v1.0")
    manager = AIManager(max_size=20)
    init_default_assistants(manager)  # 初始化默认数据

    while True:
        choice = show_menu()
        if choice == "0":
            print("✅ 退出系统，再见！")
            break

        # 1. 查看所有助手列表
        elif choice == "1":
            all_ass = manager.get_all_assistants()
            if not all_ass:
                print("❌ 当前无AI助手数据")
                continue
            print("\n所有AI助手列表：")
            for idx, ass in enumerate(all_ass, 1):
                print(f"{idx}. {ass}")

        # 2. 根据ID查询详情
        elif choice == "2":
            try:
                aid = int(input("请输入要查询的AI助手ID: "))
                ass = manager.get_assistant_by_id(aid)
                print(ass.detail_str() if ass else f"❌ 未找到ID为 {aid} 的助手")
            except ValueError:
                print("❌ ID需为数字！")

        # 3. 添加新助手
        elif choice == "3":
            handle_add_assistant(manager)

        # 4. 修改助手信息
        elif choice == "4":
            try:
                aid = int(input("请输入ID: "))
                ass = manager.get_assistant_by_id(aid)
                if not ass:
                    print(f"❌ 未找到ID为 {aid} 的助手")
                    continue
                attr, value = input("请输入要修改的属性和值（用空格分割，如score 100）: ").split(" ", 1)
                success, msg = ass.update_info(attr, value)
                print(msg)
            except ValueError:
                print("❌ 输入格式错误！需为：属性 值（如name 新名称）")
            except IndexError:
                print("❌ 输入不完整！需包含属性和值。")

        # 5. 删除助手
        elif choice == "5":
            try:
                aid = int(input("请输入要删除的AI助手ID: "))
                success, msg = manager.delete_assistant(aid)
                print(msg)
            except ValueError:
                print("❌ ID需为数字！")

        # 6. 启动服务
        elif choice == "6":
            try:
                aid = int(input("请输入要启动的AI助手ID: "))
                ass = manager.get_assistant_by_id(aid)
                if not ass:
                    print(f"❌ 未找到ID为 {aid} 的助手")
                    continue
                success, msg = ass.start_service()
                print(msg)
            except ValueError:
                print("❌ ID需为数字！")

        # 7. 停止服务
        elif choice == "7":
            try:
                aid = int(input("请输入要停止的AI助手ID: "))
                ass = manager.get_assistant_by_id(aid)
                if not ass:
                    print(f"❌ 未找到ID为 {aid} 的助手")
                    continue
                success, msg = ass.stop_service()
                print(msg)
            except ValueError:
                print("❌ ID需为数字！")

        # 8. 分配任务
        elif choice == "8":
            try:
                aid = int(input("请输入目标AI助手ID: "))
                ass = manager.get_assistant_by_id(aid)
                if not ass:
                    print(f"❌ 未找到ID为 {aid} 的助手")
                    continue
                task = input("请输入任务内容: ")
                success, msg = ass.assign_task(task)
                print(msg)
            except ValueError:
                print("❌ ID需为数字！")

        # 9. 显示统计信息
        elif choice == "9":
            stats = manager.get_statistics()
            print("\n系统统计信息：")
            print(f"总助手数: {stats['total']}")
            print(f"在线助手数: {stats['online']}")
            print(f"离线助手数: {stats['offline']}")
            print(f"平均能力评分: {stats['avg_score']:.2f}")

        # 无效选择
        else:
            print("❌ 无效操作，请重新选择！")


if __name__ == "__main__":
    main()
